// pages/delivery_type/index.js
import {
    getNavigationbar,
    RePetService
} from "../../api/index"
import china from '../../utils/daiw';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        nvaigateName: "快递类型",
        scrollViewHeight: 0,
        active: 0,
        tabsList: ['产品', '品牌介绍'],
        goodsList: [],pinyinList: [],transformedData: [],
        isSpecs: false,
        indexList: ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"],
        thumb: null,intoView: "brand-section-0",
        activity: [],
        brandList: [],
        params: {}
    },

    /**
     * 列表
     */
    getBrand() {
        getNavigationbar({
            act: 'logistics_lists',
            keyword: '',
            p: 1,
            rollpage: 10000000,
        }).then(res => {
            res.sort(function(a, b) {
                let aName = china.getSpell(a.name)
                if (china.getSpell(a.name).startsWith('[')) {
                aName = china.getSpell(a.name).substring(1,2)
                }
                let bName = china.getSpell(b.name)
                if (china.getSpell(b.name).startsWith('[')) {
                bName = china.getSpell(b.name).substring(1,2)
                }
                return (aName + '').localeCompare(bName + '')
            })
            res.forEach((element, index) => {
                let pinyinFirst = this.getPinyinFirst(element.name)
                  Object.assign(element, {
                      pinyin: pinyinFirst.substring(0,1).toLocaleUpperCase()
                  })
              });
            // 转换后的数据格式
            let transformedData = res.map((item, index) => {
                return {
                    index: index,
                    indexName: item.pinyin,
                    list: [{
                        brandName: item.name,
                        ...item
                    }]
                };
            });
            console.log('列表', transformedData)
            transformedData = this.getListByGroup(transformedData)
            wx.nextTick(() => {
                this.setData({
                    brandList: transformedData
                })
            })
        })
    },
    brandClick(e) {
        console.log('e',e)
        let val = e.currentTarget.dataset.value
      
          
          let data = {
              obj:{
                brandName: val.brandName,
                code: val.code,
                id: val.id,
                name: val.name,
                pinyin: val.pinyin
              },
              ...this.data.params
          }
          let objStr = JSON.stringify(data);
          wx.reLaunch({
            url: '/pages/add_express_numbers/index?data=' + objStr,
          });
    },
    /**
     * 获取拼音首字
     */
    getPinyinFirst(name) {
        let result = china.getSpell(name);
        if (china.getSpell(name).startsWith('[')) {
        result = china.getSpell(name).substring(1,2)
        }
        return result;
    },
     /**
     * 根据拼音首字母分组
     * @param {*} list
     */
     getListByGroup(list) {
        const map = new Map()
        list.forEach((item, index, arr) => {
          if (!map.has(item.indexName)) {
            map.set(
              item.indexName,
              arr.filter(a => a.indexName == item.indexName)
            )
          }
        })
        return Array.from(map).map(item => [...item[1]])
      },
    /**
     * 标签选择回调函数方法
     * @param {*} e 
     */
    handleSelTabs(e) {
        const {
            index
        } = e.currentTarget.dataset
        this.setData({
            active: index
        })
        RePetService({
            act: 'getBrandIntroduce',
            brand_id: this.data.params.brandid, // 供应商id
        }).then(res => {
            if (res) {
                wx.nextTick(() => {
                    this.setData({
                        goodsList: res
                    })
                })
            }
        })
    },
       /**
     * 索引栏字母点击
     * @param {*} event 
     */
       letterClick: function (e) {
        var index = e.currentTarget.dataset.index; // 获取点击的字母索引值
        var letter = this.data.indexList[index]; // 获取对应索引值的字母
        console.log('点击的字母为：', letter);
        // 调试语句，查看item数组内容
        console.log('this.data.brandList', this.data.brandList)
        var targetItem = this.data.brandList.find(item => item[0].indexName === letter); // 找到对应字母位置的item
        var indexxx = this.data.brandList.findIndex(item => item[0].indexName === letter); 
        console.log(indexxx,targetItem)
        if (targetItem && indexxx) {
            if (targetItem[0].index) {
              let targetViewId = "brand-section-" + indexxx; // 构造目标位置的id
              console.log('targetViewId', targetViewId)
                this.setData({
                    intoView: targetViewId // 更新intoView值
                });
            } else {
                console.log('未找到对应位置的item或index未定义');
            }
        } else {
            console.log('未找到对应位置的item');
        }
    },
    /**
     * 选择商品规格加入购物车回调函数方法
     */
    handleJoinCart() {
        this.setData({
            isSpecs: true
        })
    },
    /**
     * 完成规格选择将商品添加至购物车
     */
    handleConfirm() {
        this.setData({
            isSpecs: false
        })
        getApp().Tips({
            title: "商品已添加至购物车"
        })
    },
    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        let query = wx.createSelectorQuery().in(this)
        query.select('.header').boundingClientRect()
        query.exec(res => {
            let headerHeight = res[0].height;
            let winHeight; // 窗口可使用高度
            wx.getSystemInfo({
                success: (res) => {
                    winHeight = res.windowHeight
                }
            })
            let scrollHeight = winHeight - headerHeight - 40; // 滚动区域高度
            that.setData({
                scrollViewHeight: scrollHeight,
            })
        })
    },
    pinyinSort(names) {
       let name= ["顺"]

        console.log('name',name)
        //name数组
        
        var pinyinArray = new Array();
        let data = []
        for (var bukn = 0; bukn < name.length ; bukn++) {
            console.log('进来',)
            var o = new Object();
            var ken = china.getSpell(name[bukn], function (charactor, spell) {
                console.log('charactor:', charactor);
                console.log('spell:', spell);
            
                var pinyin = spell;
                if (pinyin.length === 1) {
                    data.push(pinyin[0]);
                } else {
                    spell.forEach(element => {
                        data.push(element);
                    });
                }
            });

            console.log('data',data)
            o.name = name[bukn];
            pinyinArray.push(o);
        }
        pinyinArray.forEach((element, index) => {
            Object.assign(element, {
                pinyin: data[index]
            })
        });
        console.log('pinyinArray');
        console.log(pinyinArray);
        // pinyinArray = pinyinArray.sort(compare("pinyin"))
        let map = {
            // 字段根据你用的组件名字进行更改
            letter: '',
            data: [],
        };
        pinyinArray.forEach((item, index) => {
            if (!map[item.pinyin[0].toUpperCase()]) {
                map[item.pinyin[0].toUpperCase()] = {
                    letter: item.pinyin[0].toUpperCase(),
                    data: [],
                };
            }

            this.data.pinyinList.push(item.pinyin[0].toUpperCase())
            map[item.pinyin[0].toUpperCase()].data.push(item.name);
        });
        console.log(' this.data.pinyinList', this.data.pinyinList)
        let turn = new Array();
        var letters = '*ABCDEFGHIJKLNMOPQRSTUVWXYZ'.split('');
        for (var i = 1; i < letters.length; i++) {
            if (map[letters[i]]) {
                var obj = new Object();
                //自己改改命名改成自己需要的组件名字我用的uni-index-list
                obj.letter = letters[i];
                obj.data = map[letters[i]].data;

                turn.push(obj);
            }
        }

        return turn;
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.data) {
            let params = JSON.parse(options.data)
            this.data.params = {
                ...params
            }
            console.log('进', params, this.data.params)
        }
        this.getBrand()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.computeScrollViewHeight()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})